<template>
 <div
   class="tite"
   ref="titeDom"
 >
   {{tite.value}}
 </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  Ref,
  onMounted,
  onUpdated
} from 'vue'
const EVENT_NAME = {
  moved: 'moved'
}
// import { move } from './directive'
export default defineComponent({
  name: 'tite',
  props: {
    tite: {
      required: true,
      type: Object
    }
  },
  // directives: {
  //   move
  // },
  emits: [EVENT_NAME.moved],
  setup (props, content) {
    const titeDom = ref<HTMLDivElement | null>(null)
    const emits = () => {
      content.emit(EVENT_NAME.moved, props.tite)
    }
    function move (el: HTMLElement) {
      const leftMax = props.tite.y * el.offsetWidth
      const topMax = props.tite.x * el.offsetHeight
      const speed = 10
      let left = 0
      let top = 0

      if (props.tite.previousPosition) {
        left = props.tite.previousPosition.y * el.offsetWidth
        top = props.tite.previousPosition.x * el.offsetHeight
      } else {
        left = leftMax
        top = topMax
      }
      el.style.top = top + 'px'
      el.style.left = left + 'px'
      function rowMove () {
        el.style.left = left + 'px'
        left = leftMax > left ? left + speed : left - speed
        if (left === leftMax) {
          el.style.left = left + 'px'
          emits()
          return
        }
        requestAnimationFrame(rowMove)
      }

      function colMove () {
        el.style.top = top + 'px'
        top = topMax > top ? top + speed : top - speed
        if (top === topMax) {
          el.style.top = top + 'px'
          emits()
          return
        }
        requestAnimationFrame(colMove)
      }
      if (leftMax !== left || top !== topMax) {
        requestAnimationFrame(leftMax === left ? colMove : rowMove)
      }
    }

    onUpdated(() => {
      move((titeDom as Ref<HTMLDivElement>).value)
      console.info(props.tite, `onUpdated-${props.tite.value}`)
    })
    onMounted(() => {
      console.info(props.tite, `onMounted-${props.tite.value}`)
      move((titeDom as Ref<HTMLDivElement>).value)
    })
    return {
      titeDom
    }
  }
})
</script>

<style scoped lang="less">
.tite {
  position: absolute;
  box-sizing: border-box;
  width: 50px;
  height: 50px;
  border: 3px solid #42b983;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
